package com.company.action;

import java.util.List;
import java.util.Map;

import javax.persistence.EntityManager;
import javax.persistence.NoResultException;
import javax.persistence.Query;
import javax.persistence.TypedQuery;

import model.Persona;

import org.apache.struts2.convention.annotation.Action;
import org.apache.struts2.convention.annotation.Result;
import org.apache.struts2.interceptor.SessionAware;

import com.company.common.util.Utilitario;
import com.opensymphony.xwork2.ActionContext;
import com.opensymphony.xwork2.validator.annotations.RequiredStringValidator;
import com.opensymphony.xwork2.validator.annotations.StringLengthFieldValidator;
import com.opensymphony.xwork2.validator.annotations.Validations;
import com.opensymphony.xwork2.validator.annotations.ValidatorType;

@Action(value="login",
results={
	@Result(name="exito",type="redirect",location="inicio"),
	@Result(name="error",location="/login.jsp")
} )

public class LoginAction  implements SessionAware  {

	private Persona persona;
	private String message;
	private Map<String, Object> session;
	
	@Validations(
		       requiredStrings =
		        	{  @RequiredStringValidator(type = ValidatorType.SIMPLE, fieldName = "persona.user", key = "login.persona.user.required"),
		    		   @RequiredStringValidator(type = ValidatorType.SIMPLE, fieldName = "persona.password", key = "login.persona.password.required")},
		    	stringLengthFields =
                {@StringLengthFieldValidator(type = ValidatorType.SIMPLE, trim = true, minLength="2" , maxLength = "6", fieldName = "persona.password", key = "login.persona.password.length")}
		    )
	public String execute(){
		String result="exito";
		EntityManager em = Utilitario.getInstance().getEntityManager();
		
		Query q = em.createQuery("SELECT p FROM Persona p WHERE p.user = :user");
		q.setParameter("user", persona.getUser());
		Persona personadb;
		try{
			personadb = (Persona) q.getSingleResult();
		}catch(NoResultException e){
			personadb = null;
		}
		
		
		if(personadb!=null){
			if(personadb.getPassword().equals(persona.getPassword())){
				Map<String, Object> session = ActionContext.getContext().getSession();
				session.put("persona",personadb);
			}else{
				setMessage("Password no es correcto");
				result="error";
			}
		}else{
			setMessage("Usuario no esta registrado");
			result="error";
		}
		
		return result;
	}

	public Persona getPersona() {
		return persona;
	}

	public void setPersona(Persona persona) {
		this.persona = persona;
	}

	public String getMessage() {
		return message;
	}

	public void setMessage(String message) {
		this.message = message;
	}

	
    public Map<String, Object> getSession() {
         return session;
    }
    public void setSession(Map<String, Object> session) {
         this.session = session;
    }
	
}
